<template>
  <div>
    <el-form label-width="80px">
      <el-form-item label="SKU名称">
        <el-input placeholder="SKU名称" v-model="skuParams.skuName"></el-input>
      </el-form-item>
      <el-form-item label="价格(元)">
        <el-input
          placeholder="价格(元)"
          type="number"
          v-model="skuParams.price"
        ></el-input>
      </el-form-item>
      <el-form-item label="重量(元)">
        <el-input
          placeholder="重量(元)"
          type="number"
          v-model="skuParams.weight"
        ></el-input>
      </el-form-item>
      <el-form-item label="SKU描述">
        <el-input
          placeholder="SKU描述"
          type="textarea"
          v-model="skuParams.skuDesc"
        ></el-input>
      </el-form-item>
      <el-form-item label="平台属性">
        <el-form :inline="true">
          <el-form-item
            label-width="100"
            style="margin: 5px 0px"
            v-for="(item, index) in attrArr"
            :key="item.id"
            :label="item.attrName"
          >
            <el-select v-model="item.attrIdAndValueId">
              <el-option
                :value="`${item.id}:${attrValue.id}`"
                v-for="(attrValue, index) in item.attrValueList"
                :key="attrValue.id"
                :label="attrValue.valueName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-form :inline="true">
          <el-form-item
            label-width="100"
            v-for="(item, index) in saleArr"
            :key="item.id"
            :label="item.saleAttrName"
          >
            <el-select v-model="item.saleIdAndValueId">
              <el-option
                :value="`${item.id}:${saleAttr.id}`"
                v-for="(saleAttr, index) in item.spuSaleAttrValueList"
                :key="saleAttr.id"
                :label="saleAttr.saleAttrName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-form-item>
      <el-form-item label="图片名称">
        <el-table border :data="imgArr" ref="table">
          <el-table-column
            type="selection"
            width="80"
            align="center"
          ></el-table-column>
          <el-table-column label="图片">
            <template #="{ row, $index }">
              <img
                :src="row.imgUrl"
                alt="商品图片"
                style="width: 100px; height: 100px"
              />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"></el-table-column>
          <el-table-column label="操作">
            <template #="{ row, $index }">
              <el-button size="small" type="primary" @click="handler(row)">
                设置默认
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button @click="save" type="primary" size="default">保存</el-button>
        <el-button size="default" @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
// 引入请求API
import { reqAttr } from '../../../api/product/attr'
import {
  reqSpuImageList,
  reqSupHasSaleAttr,
  reqAddSku,
} from '../../../api/product/spu'
// 引入ts类型
import { AttrResponseData, Attr } from '../../../api/product/attr/type'
import {
  SpuHasImg,
  SaleAttrResponseData,
  SaleAttr,
  SpuImg,
  SkuData,
} from '../../../api/product/spu/type'

import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
// 获取table组件实例
let table = ref<any>()
// 收集SKU的参数
let skuParams = reactive<SkuData>({
  // 父组件传递过来的数据
  category3Id: '',
  spuId: '',
  tmId: '',
  // v-model收集
  skuName: '',
  price: '',
  weight: '',
  skuDesc: '',
  skuAttrValueList: [],
  skuSaleAttrValueList: [],
  skuDefaultImg: '',
})
// 已有的属性
let attrArr = ref<Attr[]>([])
// 照片墙的数据
let imgArr = ref<SpuImg[]>([])
// 已有的销售属性
let saleArr = ref<SaleAttr[]>([])
//当前子组件的方法对外暴露
const initSkuData = async (
  c1Id: string | number,
  c2Id: string | number,
  spu: any,
) => {
  // 收集数据
  skuParams.category3Id = spu.category3Id
  skuParams.spuId = spu.id
  skuParams.tmId = spu.tmId
  // 获取已有的SPU属性数据
  const result: AttrResponseData = await reqAttr(c1Id, c2Id, spu.category3Id)
  // 获取照片墙的数据
  const result1: SpuHasImg = await reqSpuImageList(spu.id)
  // 获取已有的销售属性
  const result2: SaleAttrResponseData = await reqSupHasSaleAttr(spu.id)

  // 存储已有的属性
  attrArr.value = result.data
  // 存储照片墙的数据
  imgArr.value = result1.data
  // 存储已有的销售属性
  saleArr.value = result2.data
}
let $emit = defineEmits(['changeScene'])
//点击取消按钮:通知父组件切换场景为1,展示有的SPU的数据
const cancel = () => {
  $emit('changeScene', { flag: 0, params: 'update' })
}
// 设置默认图片的方法回调
const handler = (row: any) => {
  // 点击的时候，先是全部图片的复选框都不勾选
  imgArr.value.forEach((item: any) => {
    table.value.toggleRowSelection(item, false)
  })
  // 再勾选需要勾选的
  table.value.toggleRowSelection(row, true)
  // 赋值给默认图片
  skuParams.skuDefaultImg = row.imgUrl
}
// 保存按钮的回调
const save = async () => {
  // 整理参数
  // 平台属性
  skuParams.skuAttrValueList = attrArr.value.reduce((prev: any, next: any) => {
    // 如果有收集到的数据
    if (next.attrIdAndValueId) {
      let [attrId, valueId] = next.attrIdAndValueId.split(':')
      // 向prev中push一个对象
      prev.push({
        attrId,
        valueId,
      })
    }
    return prev
  }, [])
  // 销售属性
  skuParams.skuSaleAttrValueList = saleArr.value.reduce(
    (prev: any, next: any) => {
      if (next.saleIdAndValueId) {
        let [saleAttrId, saleAttrValueId] = next.saleIdAndValueId.split(':')
        prev.push({
          saleAttrId,
          saleAttrValueId,
        })
      }
      return prev
    },
    [],
  )
  // 发送添加SKU的请求
  const result: any = await reqAddSku(skuParams)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '添加SKU成功',
    })
    //通知父组件切换场景为零
    $emit('changeScene', { flag: 0, params: '' })
  } else {
    ElMessage({
      type: 'error',
      message: '添加SKU失败',
    })
  }
}
//对外暴露方法
defineExpose({
  initSkuData,
})
</script>

<style scoped></style>
